package dm1101.demo02;

import java.util.Arrays;

/**
 * @author Ln
 * @version 终极版
 * @date 2022/11/1 14:58
 */
public class InstantLock {
    private static String[] arr=new String[2];
    private static int index=0;
    //自动锁
    private static Object lock=new Object();
    public static void main(String[] args) {
        Thread t1=new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    if (arr[index] == null) {
                        arr[index] = "你好";
                        index++;
                    }
                }
            }
        });

        Thread t2=new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    if (arr[index] == null) {
                        arr[index] = "世界";
                        index++;
                    }
                }
            }
        });

        t1.start();
        t2.start();

        //不能直接打印arr,因为main线程可能先获取cpu
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Arrays.toString(arr));
    }
}
